package tq.com.tqstudent.ui.activity.classes;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.cropimage.tq.ImagePicker;
import com.cropimage.tq.cropper.CropImage;
import com.cropimage.tq.cropper.CropImageView;
import com.google.gson.Gson;
import com.lib.common.base.BaseActivity;
import com.lib.common.utils.FileUtil;
import com.lib.common.utils.ImgUtils;
import com.lib.common.utils.LogUtil;
import com.lib.common.utils.PermissionConstant;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;
import com.zhihu.matisse.listener.OnSelectedListener;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import tq.com.tqstudent.App;
import tq.com.tqstudent.Constants;
import tq.com.tqstudent.R;
import tq.com.tqstudent.adapter.common.CommonAdapter;
import tq.com.tqstudent.adapter.common.MultiItemTypeAdapter;
import tq.com.tqstudent.adapter.common.ViewHolder;
import tq.com.tqstudent.bean.BaseBean;
import tq.com.tqstudent.bean.MalistBean;
import tq.com.tqstudent.bean.ShareImageBean;
import tq.com.tqstudent.bean.SimpleBaseBean;
import tq.com.tqstudent.bean.event.ShareSuccessEvent;
import tq.com.tqstudent.bean.params.ShareClassParams;
import tq.com.tqstudent.net.ok.DialogCallback;
import tq.com.tqstudent.net.ok.SimpleDialogCallback;
import tq.com.tqstudent.net.ok.StringCallback;
import tq.com.tqstudent.ui.activity.mine.HeadImgActivity;
import tq.com.tqstudent.utils.MatisseImageEngine;
import tq.com.tqstudent.utils.VarietyUtil;
import tq.com.tqstudent.views.PhotoTipsDialog;
import tq.com.tqstudent.widgets.PreviewImgActivity;

/**
 * @Author rames
 * @date 2019/4/1 16:24
 */
public class ShareClassActivity extends BaseActivity {
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.title_edit)
    EditText titleEdit;
    private static final int MAX_IMAGE_SIZE = 4; // 最多只能选8张图片
    private ArrayList<ShareImageBean> imgList;
    private CommonAdapter adapter;
    private int shareID;
    private ImagePicker imagePicker;
    private ArrayList<String> uploadUrl = new ArrayList<>(); // 上传成功后的图片的服务器路径

    public static void show(Activity activity, int shareID) {
        Intent intent = new Intent(activity, ShareClassActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt("shareID", shareID);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    @Override
    protected void getExtras(Bundle extras) {
        shareID = extras.getInt("shareID");
    }

    @Override
    public int initLayout() {
        return R.layout.activity_share_class;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        setTitle("分享");
        imgList = new ArrayList<>();
        initImagePicker();

        ShareImageBean bean = new ShareImageBean();
        bean.isAdd = true;
        imgList.add(bean);

        StaggeredGridLayoutManager staggered = new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(staggered);
        adapter = new CommonAdapter<ShareImageBean>(this, R.layout.item_share_class, imgList) {
            @Override
            protected void convert(ViewHolder holder, ShareImageBean bean, int position) {
                ImageView image = holder.getView(R.id.image);

                if (bean.isAdd) {
                    image.setImageResource(R.mipmap.icon_add);
                    holder.setInvisible(R.id.delete_layout, false);
                } else {
                    Glide.with(ShareClassActivity.this).load(new File(bean.path)).into(image);
                    holder.setInvisible(R.id.delete_layout, true);

                    holder.setOnClickListener(R.id.delete_layout, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            deleteImage(position);
                        }
                    });
                }
            }
        };
        recyclerView.setAdapter(adapter);

        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if(imgList.get(position).isAdd) {
                    PhotoTipsDialog dialog = new PhotoTipsDialog(ShareClassActivity.this);
                    dialog.setCallback(chooseCallback);
                    dialog.show();
                } else {
//                    ArrayList<String> list = new ArrayList<>();
//                    for (int i = 0; i < imgList.size(); i++) {
//                        if(!imgList.get(i).isAdd) {
//                            list.add(imgList.get(i).path);
//                        }
//                    }
//                    PreviewImgActivity.show(ShareClassActivity.this, list, 0);
                }
            }
        });
    }

    private void initImagePicker(){
        imagePicker = new ImagePicker();
        // 设置标题
        imagePicker.setTitle("");
        // 设置是否裁剪图片
        imagePicker.setCropImage(true);
        imagePicker.setCallback(cropCallback);
    }

    private ImagePicker.Callback cropCallback = new ImagePicker.Callback(){
        // 选择图片回调
        @Override public void onPickImage(Uri imageUri) {

        }

        // 裁剪图片回调
        @Override public void onCropImage(Uri imageUri) {
            images.clear();
            LogUtil.e("imageUri: "+imageUri.getPath()+" | filePath: "+FileUtil.getFilePathByUri(ShareClassActivity.this, imageUri));
            images.add(FileUtil.getFilePathByUri(ShareClassActivity.this, imageUri));
            imageComplete();
        }

        // 自定义裁剪配置
        @Override public void cropConfig(CropImage.ActivityBuilder builder) {
            VarietyUtil.initCropBuilder(builder);
        }

        // 用户拒绝授权回调
        @Override public void onPermissionDenied(int requestCode, String[] permissions, int[] grantResults) {
        }
    };

    private PhotoTipsDialog.ChooseCallback chooseCallback = new PhotoTipsDialog.ChooseCallback() {
        @Override
        public void choose(int index) {
            // 相机
            if(index == 1){
                getPermission(true);

                // 相册
            } else if (index == 2){
                getPermission(false);

                // 保存
            } else { }
        }
    };

    private void deleteImage(int position){
        imgList.remove(position);
        boolean isHaveAdd = false;
        for (int i = 0; i < imgList.size(); i++) {
            if(imgList.get(i).isAdd){
                isHaveAdd = true;
                break;
            }
        }

        if(!isHaveAdd){
            ShareImageBean bean = new ShareImageBean();
            bean.isAdd = true;
            imgList.add(bean);
        }
        adapter.notifyDataSetChanged();
    }

    private void getPermission(boolean isCamera){
        AndPermission.with(this)
                .runtime()
                .permission(PermissionConstant.PERMISSIONS_OF_IMAGE)
                .onGranted(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> permissions) {
                        imagePicker(isCamera);
                    }
                })
                .onDenied(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> permissions) {
                        showToast("用户已禁止访问图片权限");
                    }
                })
                .start();
    }

    private int getMaxImageSize(){
        int max = MAX_IMAGE_SIZE;
        for (int i = 0; i < imgList.size(); i++) {
            if(!imgList.get(i).isAdd){
                max--;
            }
        }
        return max;
    }

    @OnClick(R.id.share_text)
    public void onClick(View view) {
        if(view.getId() == R.id.share_text){
            if(check()) {
                index = 0;
                showLoading();
                uploadImageTask(imgList.get(0).path);
            }
        }
    }

    private boolean check(){
        if(titleEdit.getText().toString().trim().length() < 1){
            showToast("请填写标题!");
            return false;
        }

        if(imgList.size() < 2){
            showToast("请选择图片!");
            return false;
        }

        return true;
    }

    private void imagePicker(boolean isCamera) {
        Matisse.from(this)
                .choose(MimeType.of(MimeType.PNG, MimeType.JPEG))
                .countable(true)
                .maxSelectable(1)
                .capture(false)
                .isCamera(isCamera)
                .isSimpleChoose(true)
                .captureStrategy(new CaptureStrategy(true, "tq.com.tqstudent.fileProvider"))
//                .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.dp_120))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new MatisseImageEngine())
                .forResult(REQUEST_CODE_CHOOSE);
    }

    private List<String> images = new ArrayList<>();
    private final int REQUEST_CODE_CHOOSE = 1355;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            imagePicker.handlePickImage(this, Matisse.obtainPathResult(data).get(0));
        } else {
            imagePicker.onActivityResult(this, requestCode, resultCode, data);
        }
    }

    /** 图片选择成功后的处理 */
    private void imageComplete(){
        for (int i = imgList.size()-1; i >= 0; i--) {
            if(imgList.get(i).isAdd){
                imgList.remove(i);
                break;
            }
        }

        for (int i = 0; i < images.size(); i++) {
            ShareImageBean bean = new ShareImageBean();
            bean.path = images.get(i);
            bean.isAdd = false;
            imgList.add(bean);
        }

        if(imgList.size() < MAX_IMAGE_SIZE){
            ShareImageBean bean = new ShareImageBean();
            bean.isAdd = true;
            imgList.add(bean);
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void initData() { }

    private void share(){
        OkGo.<BaseBean<MalistBean>>post(App.getHttpUrl("api/clz/ma"))
                .tag(this)
                .upJson(initJson())
                .execute(new DialogCallback<MalistBean>(this){
                    @Override
                    public void handleSuccess(MalistBean data) {
                        showToast("分享成功");
                        EventBus.getDefault().post(new ShareSuccessEvent());
                        finish();
                    }
                });
    }

    private String initJson(){
        StringBuffer url = new StringBuffer();
        for (int i = 0; i < uploadUrl.size(); i++) {
            url.append(uploadUrl.get(i));
            if(i != uploadUrl.size()-1){
                url.append(",");
            }
        }

        ShareClassParams params = new ShareClassParams();
        params.material_id = shareID;
        params.title = titleEdit.getText().toString().trim();
        params.content = url.toString();
        params.content_type = "18";
        params.content_cover = uploadUrl.get(0);

        return new Gson().toJson(params, ShareClassParams.class);
    }

    private int index = 0; // 上传的第几张图
    /**
     * 上传头像(单张)
     * @param path
     */
    private void uploadImageTask(String path){
        OkGo.<SimpleBaseBean>post(App.getUploadUrl())
                .tag(this)
                .isMultipart(true)
                .params("file_type", "jpg|jpeg|png")
                .params("file_tag", "share image")
                .params("file", new File(path))
                .execute(new SimpleDialogCallback(this, false) {
                    @Override
                    public void handleSuccess(SimpleBaseBean data) {
                        if(data.isSuccess()){
                            uploadUrl.add(data.fid);
                            index++;
                            if(index < imgList.size() && !imgList.get(index).isAdd) {
                                uploadImageTask(imgList.get(index).path);
                            } else {
                                dismissLoading();
                                showToast("图片上传完成");
                                share();
                            }
                        }
                    }

                    @Override
                    public void onFinish() {
                        dismissLoading();
                    }

                    @Override
                    public void uploadProgress(Progress progress) {
                        LogUtil.e("第"+ index+"张Progress: "+progress);
                    }
                });
    }

    /** 上传分享的图片(多张) */
    private void uploadImagesTask(List<String> paths){
        PostRequest<String> request = OkGo.<String>post(Constants.HTTP_UPLOAD_URL)
                .tag(this)
                .isMultipart(true)
                .params("file_type", "jpg")
                .params("file_tag", "share image");

        for (int i = 0; i < paths.size(); i++) {
            request.params("file" + (i + 1), new File(paths.get(i)));
        }

        request.execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                LogUtil.e("onSuccess");
            }

            @Override
            public void uploadProgress(Progress progress) {
                LogUtil.e("Progress: "+progress);
            }
        });
    }
}
